package com.sunny.netty.handler;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
 * 换行符解析器服务端
 *
 * @author sunny
 * @date 2018/12/4
 */
public class LineBasedFrameDecoderServerHandler extends ChannelInitializer {
    @Override
    protected void initChannel(Channel channel) throws Exception {
        //添加一个基于行的解码器 解决粘包拆包的问题 它是根据\n或者\r\n判断的
        channel.pipeline().addLast(new LineBasedFrameDecoder(1024));
        channel.pipeline().addLast(new StringDecoder());
        //创建channel通道 往通道中添加io事件处理类
        channel.pipeline().addLast(new LineBasedServerHandler());
    }

    private static class LineBasedServerHandler extends ChannelHandlerAdapter {

        private int counter;

        /**
         * 处理一些异常情况
         *
         * @param ctx
         * @param cause
         * @author sunny
         * @date 2018/12/4
         * @return void
         */
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            //发生异常时，执行重写后的exceptionCaught进行资源关闭
           ctx.close();
        }

        /**
         * 接收客户端的内容
         *
         * @param ctx
         * @param msg
         * @author sunny
         * @date 2018/12/4
         * @return void
         */
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            //channelRead方法中的msg参数（服务器接收到的客户端发送的消息）强制转换成ByteBuf
            String body = (String) msg;
            System.out.println("server 接收消息：" + body + "; 当前统计：" + ++counter);
            String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? String.valueOf(System.currentTimeMillis()) + "\n" : "BAD ORDER";
            ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
            //将消息放入缓冲数组
            ctx.write(resp);
        }

        /**
         * 刷新
         *
         * @param ctx
         * @author sunny
         * @date 2018/12/4
         * @return void
         */
        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            //将消息队列中信息写入到SocketChannel中，解决了频繁唤醒Selector所带来的不必要的性能开销
            //Netty的write只是将消息放入缓冲数组，再通过调用flush才会把缓冲区的数据写入到SocketChannel
            ctx.flush();
        }
    }

    public static void bind(int port) {
        //创建线程组
        NioEventLoopGroup masterGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {

            //创建NIO服务端启动辅助类
            ServerBootstrap bootstrap = new ServerBootstrap();

            bootstrap.group(masterGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    //服务端的连接数
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    //服务端消息不延迟，立即推送
                    .option(ChannelOption.TCP_NODELAY, true)
                    //行分割解码
                    .childHandler(new LineBasedFrameDecoderServerHandler());

            //绑定端口，同步等待成功
            System.out.println("绑定端口，同步等待成功。。。。");
            ChannelFuture future = bootstrap.bind(port).sync();

            //等待服务端监听端口关闭
            future.channel().closeFuture().sync();
            System.out.println("等待服务端监听端口关闭。。。。");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //优雅退出释放线程池
            masterGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            System.out.println("优雅退出释放线程池。。。。");
        }

    }

    public static void main(String[] args) {
        LineBasedFrameDecoderServerHandler.bind(4040);
    }
}
